/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modeles.servicesClient;

import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;

/**
 *
 * @author Fred
 */
public class Services {

    private WebTarget webTarget;
    private Client client;
    private static final String BASE_URI = "http://192.168.128.13:8081/Dared/shop/admin"; //à changer 192.168.128.13

    public Services(String path) {
        client = javax.ws.rs.client.ClientBuilder.newClient();
        webTarget = client.target(BASE_URI).path(path);
    }

    public Integer remove(String id) throws ClientErrorException {
        Response r = webTarget.path(java.text.MessageFormat.format("{0}", new Object[]{id})).request().delete();
        return isSucces(r) ? null : r.getStatus();
    }

    public <T> T findById(Class<T> responseType, String id) throws ClientErrorException {
        WebTarget resource = webTarget;
        resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
        return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

    public <T> T findAll(GenericType<T> responseType) throws ClientErrorException {
        WebTarget resource = webTarget;
        T t = resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
        return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
    }

    public boolean edit(Object requestEntity, String id) throws ClientErrorException {
        return isSucces(webTarget.path(java.text.MessageFormat.format("{0}", new Object[]{id})).request(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON)));
    }

    public boolean create(Object requestEntity) throws ClientErrorException {
        return isSucces(webTarget.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON)));        
    }

    public void close() {
        client.close();
    }

    protected WebTarget getWebTarget() {
        return webTarget;
    }
    
    protected boolean isSucces(Response r){
        return r.getStatus() >= 200 && r.getStatus() <= 299;
    }
}
